package com.lingkang.usersso.controller;

import com.alibaba.fastjson.JSONObject;
import com.lingkang.usersso.dto.ResponseResult;
import com.lingkang.usersso.entity.UsUser;
import com.lingkang.usersso.service.UserService;
import com.lingkang.usersso.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linke
 * @date 2020-02-05 下午 16:30
 * @description
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Value("${myServer.ip}")
    private String ip;
    @Value("${server.port}")
    private int port;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;

    /**
     * 导航页面 start
     */
    @GetMapping(value = {"index"})
    public String index() {
        return "index";
    }

    @GetMapping("welcome")
    public String welcome() {
        return "welcome";
    }

    @GetMapping("userList")
    public String userList(){
        return "user-list";
    }

    /**
     * 导航页面 end
     */


    @PostMapping("login")
    @ResponseBody
    public Object login() throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        map.put("client_id", "client");
        map.put("grant_type", "password");
        map.put("client_secret", "secret");
        String res = HttpUtils.post(String.format("http://%s:%d/oauth/token", ip, port), map);
        JSONObject json = JSONObject.parseObject(res);
        if (json.getString("access_token") != null) {
            ResponseResult responseResult = new ResponseResult();
            responseResult.setCode(20000);
            responseResult.setData(json);
            String service = request.getParameter("service");
            userService.addLoginLog(username, String.format("%s%s", "来源服务：", service), HttpUtils.getIpAddress(request));
            return responseResult;
        } else {
            if (json.getString("error_description").indexOf("不") != -1) {
                return new ResponseResult<>(20002, "账号不存在！");
            } else {
                return new ResponseResult<>(20002, "密码错误！");
            }
        }
    }

    @PostMapping("toLogin")
    @ResponseBody
    public Object toLogin() throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UsUser user = userService.getUserInfo(username);
        if (user == null) {
            return "账号不存在！";
        }
        if (!user.getPassword().equals(password)) {
            return "密码错误！";
        }
        List<String> roles = userService.getRoleByUserId(user.getId());
        for (String r : roles) {
            if (r.equals("ROLE_SUPER")) {
                request.getSession().setAttribute("user", user);
                userService.addLoginLog(username, "用户管理系统登陆", HttpUtils.getIpAddress(request));
                return "success";
            }
        }
        return "当前账号不存在登陆权限！";
    }

}
